package com.tehui.activity.impl;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.tehui.R;
import com.tehui.activity.BaseActivity;
import com.tehui.utils.tools.MD5Encoder;
import com.tehui.utils.tools.PhoneUtils;
import com.tehui.utils.ui.UiUtils;
import com.tehui.utils.web.MyCallback;
import com.tehui.utils.web.NR;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class ForgetActivity extends BaseActivity {

    private static final int CODE_ING       = 1;   //已发送，倒计时
    private static final int CODE_REPEAT    = 2;  //重新发送
    private static final int SMSDDK_HANDLER = 3;  //短信回调
    private              int TIME           = 60;//倒计时60s

    @BindView(R.id.etNum)
    EditText etNum;
    @BindView(R.id.etAuth)
    EditText etAuth;
    @BindView(R.id.etNewPsw)
    EditText etNewPsw;
    @BindView(R.id.btnAuth)
    Button   btnAuth;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_forget;
    }

    @Override
    public void initActivityData() {
        super.initActivityData();
        tvTitle.setText("忘记密码");
    }

    @OnClick({R.id.btnAuth, R.id.btnOK})
    public void onClick(View view) {
        String phone = etNum.getText().toString().trim();
        switch (view.getId()) {
            case R.id.btnAuth:
                if (TextUtils.isEmpty(phone)) {
                    UiUtils.toast("电话号码不能为空");
                    return;
                }

                if (!PhoneUtils.isChinaPhoneLegal(phone)) {
                    UiUtils.toast("您输入的电话号码有误,请重新输入");
                    return;
                }
                requestSMS(phone);
                break;
            case R.id.btnOK:
                String auth = etAuth.getText().toString().trim();
                String password = etNewPsw.getText().toString().trim();
                if (TextUtils.isEmpty(auth)) {
                    UiUtils.toast("请填写验证码");
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    UiUtils.toast("请填写新密码");
                    return;
                }
                changePassword(phone, auth, password);
                break;
        }
    }

    private void changePassword(String phone, String auth, String password) {
        try {
            String encode = MD5Encoder.encode(password);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("phone", phone);
            jsonObject.put("code", auth);
            jsonObject.put("password", encode);
            String s = jsonObject.toString();
            NR.postRequest("http://dl.21tehui.com/TkPhoneChangePwdApi", "str", s, this, new MyCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    super.onSuccess(s, call, response);
                    try {
                        JSONObject jsonObject1 = new JSONObject(s);
                        String info = jsonObject1.getString("info");
                        if (info != null) {
                            if (info.equals("1")) {
                                UiUtils.toast("修改成功");
                            } else if (info.equals("2")) {
                                UiUtils.toast("验证码错误");
                            } else if (info.equals("3")) {
                                UiUtils.toast("没有此用户");
                            } else {
                                UiUtils.toast("注册失败,请稍候重试");
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Call call, Response response, Exception e) {
                    super.onError(call, response, e);
                    UiUtils.toast("服务器异常,请稍候重试");
                }
            });
        } catch (Exception e) {
        }
    }

    //请求验证码
    private void requestSMS(String phone) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("phone", phone);
            String s = jsonObject.toString();
            NR.postRequest("http://dl.21tehui.com/TkPhoneChangePwdApi/noteSend", "str", s, this, new
                    MyCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    super.onSuccess(s, call, response);
                    if (s != null) {
                        try {
                            JSONObject jsonObject1 = new JSONObject(s);
                            String info = jsonObject1.getString("info");
                            if (info.equals("1")) {
                                sendMessage();
                                UiUtils.toast("发送成功");
                            } else if (info.equals("2")) {
                                UiUtils.toast("手机号码有误");
                            } else if (info.equals("3")) {
                                UiUtils.toast("没有当前用户");
                            } else if (info.equals("4")) {
                                UiUtils.toast("发送过于频繁,请稍候重试");
                            } else {
                                UiUtils.toast("发送失败");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(Call call, Response response, Exception e) {
                    super.onError(call, response, e);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void sendMessage() {
        btnAuth.setClickable(false);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 60; i > 0; i--) {
                    handler.sendEmptyMessage(CODE_ING);
                    if (i <= 0) {
                        break;
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                handler.sendEmptyMessage(CODE_REPEAT);
            }
        }).start();
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CODE_ING://已发送,倒计时
                    btnAuth.setText("重新发送(" + --TIME + "s)");
                    break;
                case CODE_REPEAT://重新发送
                    btnAuth.setText("获取验证码");
                    btnAuth.setClickable(true);
                    TIME = 60;
                    break;
                case SMSDDK_HANDLER:
                    int event = msg.arg1;
                    int result = msg.arg2;
                    Object data = msg.obj;
                    break;
            }
        }
    };
}
